<?php

/**

 * 考勤管理
 * 
 * @access  public 
 * @author  qiaoshoujuan<qiao_sj@jsumt.com.cn> 
 */

namespace Home\Controller;

use Think\Controller;

class AttendanceController extends BaseController {
    public function _initialize() {
        parent::_initialize();
        $this->limit = 10;
        
        //获取部门
        $map['dept_name'] = array('notlike','%公司领导%');
        $depts = M('department')->field('dept_id,dept_name')->where($map)->order('dept_no')->select();
        $this->depts = $depts;
        
        //获取当前用户的部门
        $umap['dept_id'] = session('dept_id');
        $userDept = M('department')->field('dept_id,dept_name')->where($umap)->find();
        $this->userDept = $userDept;
        
        $this->user_id = session('user_id');
        $this->dept_id = session('dept_id');
    }
    
    //判断是否是节假日
    public function check_holiday($day)
    {
        $is_holiday=0;
        $data = M('attend_holiday')->where('begin_date <= "'.$day.'" and end_date >= "'.$day.'"')->find();
        if($data)
            $is_holiday=1;
        return $is_holiday;
    }
    
    //判断是否是双休日
    function check_holiday1($day,$general)
    {
        $is_holiday1=0;
        $week=date("w",strtotime($day));
        if($week == 6 || $week == 0){
            $is_holiday1=1;
        }
        return $is_holiday1;
    }
    
    //判断是否出差
    function check_evection($user_id,$day)
    {
        $is_evection=0;
        $data = M('attend_evection')->where('user_id = "'.$user_id.'" and allow in(0,1) and to_days(evection_date1)<=to_days("'.$day.'") and to_days(evection_date2)>=to_days("'.$day.'")')->find();
        if($data)
            $is_evection=1;
        return $is_evection;
    }
    
    //判断是否请假
    function check_leave($user_id,$day,$duty_time)
    {
        $is_leave=0;
        $data = M('attend_leave')->where('user_id = "'.$user_id.'" and (allow="1" or allow="0") and (leave_date1 like "%'.$day.'%" or leave_date2 like "%'.$day.'%")')->find();
        if($data)
        {
            $is_leave=$data['leave_duration'];
            $leave_type2=$data["leave_type2"];
        }
        return $is_leave;
    }
    
    //判断是否外出
    public function check_out($user_id,$day,$duty_time)
    {
        $is_out=0;
        $data = M('attend_out')->where('user_id = "'.$user_id.'" and allow in(0,1) and to_days(SUBMIT_TIME)=to_days("'.$day.'") and out_time1<="'.substr($duty_time,0,strrpos($duty_time,":")).'" and out_time2>="'.substr($duty_time,0,strrpos($duty_time,":")).'"')->find();
        if($data)
            $is_out=1;
        return $is_out;
    }
    
    public function compare_time($time1,$time2) //-- time1=time2 返回0,time1>time2 返回1,time1<time2 返回-1
    {
        $str=strtok($time1,":");
        $hour1=$str;
        $str=strtok(":");
        $min1=$str;
        $str=strtok(":");
        $sec1=$str;

        $str=strtok($time2,":");
        $hour2=$str;
        $str=strtok(":");
        $min2=$str;
        $str=strtok(":");
        $sec2=$str;

        if($hour1>$hour2)
            return 1;
        else if($hour1<$hour2)
            return -1;
        else
        {
            if($min1>$min2)
                return 1;
            else if($min1<$min2)
                return -1;
            else
            {
                if($sec1>$sec2)
                    return 1;
                else if($sec1<$sec2)
                    return -1;
                else
                    return 0;
            }
        }
    }
    
    public function statistics(){
        $condition = I('get.');
        
        //获取当前用户所在部门的当年的考勤数据
        $dept_id = M('department')->where('dept_name like "%公司领导%"')->getField('dept_id');
        $priv_no = M('user_priv')->where('user_priv like "%'.session('user_priv').'%"')->getField('priv_no');
        if($dept_id != session('dept_id') && $priv_no > 40){//普通员工
            $where = 'd.dept_id = u.dept_id and u.user_priv = p.user_priv and u.user_id = "'.session('user_id').'"';
            $deptUsers = M('user')->field('user_id,user_name')->where('dept_id = '.session('dept_id'))->select();
            $this->class = '1';
        }else{//领导层
            if($dept_id != session('dept_id') && session('user_id') != 'admin'){//部门领导
                if(isset($condition['dept_id'])){
                    $this->dept_id = $condition['dept_id'];
                    $where = 'd.dept_id in( '.$condition['dept_id'].')';
                    $deptUsers = M('user')->field('user_id,user_name')->where('dept_id = '.$condition['dept_id'])->select();

                }else{
                    $this->dept_id = session('dept_id');
                    $where = 'd.dept_id in ('.session('dept_id').')';
                    $deptUsers = M('user')->field('user_id,user_name')->where('dept_id = '.session('dept_id'))->select();

                }
                if(isset($condition['user_id'])){
                    $this->user_id = $condition['user_id'];
                    $where .= " and u.user_id = '".$condition['user_id']."'";
                }
                $this->class = '1';
            }else{//公司领导
                if(isset($condition['dept_id'])){
                    $this->dept_id = $condition['dept_id'];
                    $where = 'd.dept_id in( '.$condition['dept_id'].')';
                    $deptUsers = M('user')->field('user_id,user_name')->where('dept_id = '.$condition['dept_id'])->select();
                }else{
                    $this->dept_id = '143';
                    $where = 'd.dept_name like "%综合部%"';
                    $deptUsers = M('user')->field('user_id,user_name')->where('dept_id = 143')->select();
                }
                if(isset($condition['user_id']) && $condition['user_id'] != ''){
                    $this->user_id = $condition['user_id'];
                    $where .= " and u.user_id = '".$condition['user_id']."'";
                }
                $this->class = '0';
            }
            $where .= ' and d.dept_id = u.dept_id and u.user_priv = p.user_priv and u.user_id != "admin"';
        }
        $users = M()->table('user u,user_priv p,department d')->field('u.user_name,u.user_id,d.dept_name,u.dept_id')->where($where)->select();
            
        //默认在本年本月的考勤数据
            $date1 = date('Y-m-01');
            $date2 = date('Y-m-d');
        foreach($users as $k=>$v){
            $user_name=$v["user_name"];
            $dept_name=$v["dept_name"];
            $user_id=$v["user_id"];
            $dept_id=$v["dept_id"];
            
            $count_array[$k]['dept_name']=$dept_name;
            $count_array[$k]['user_name']=$user_name;
            $count_array[$k]['user_id']=$user_id;
            $count_array[$k]['dept_id']=$dept_id;
            $p = 0;
            $attend = $this->getAttend($date1,$date2,$user_id);
            $count_array[$k]['all_total'] = $attend['all_total'];
            $count_array[$k]['evection'] = $attend['evection'];
            $count_array[$k]['late'] = $attend['late'];
            $count_array[$k]['early'] = $attend['early'];
            
            //剩余假期
            $userinfo = M('userinfo')->where('user_id="'.$v['user_id'].'"')->find();
            $count_array[$k]['year'] = $userinfo['able_year'];
            $count_array[$k]['vacation'] = $userinfo['able_vacation'];
            
                        }
//        die;
        $this->deptUsers = $deptUsers;
        $this->count = count($count_array);
        $this->priv_no = $priv_no;
        $this->count_array = $count_array;
        $this->display();
                    }
    
    public function absence(){
        if(IS_AJAX){
            $data = I('get.');
            $out = $this->getAbsence($data);
            $out['pages'] = $this->pageLists($out['count']);
            $this->ajaxReturn($out);
                }
        $condition = I('get.');
        $out = $this->getAbsence($condition);
        $this->class = $out['class'];
        $this->contime = $out['contime'];
        if(isset($out['dept_id']))
            $this->dept_id = $out['dept_id'];
                
        $this->count = count($out['data']);
        $this->out = $out['data'];
        $this->display();
                }
                
    public function delAbsence(){
        $data = I('get.');
        $map['run_id'] = $data['run_id'];
        $res = M('attend_'.$data['type'])->where($map)->delete();
        if($res){
            $return['status'] = 1;
                
        }else{
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }
                
    public function getAbsence($condition){
        $out = array();
        $out['type'] = $condition['type'];
        //获取当前用户所在部门的当月的缺勤数据
        $dept_id = M('department')->where('dept_name like "%公司领导%"')->getField('dept_id');
        $priv_no = M('user_priv')->where('user_priv like "%'.session('user_priv').'%"')->getField('priv_no');
        if($dept_id != session('dept_id') && $priv_no > 40){//普通员工
            $where = 't.run_id = r.run_id and r.run_id = d.run_id and t.user_id = "'.session('user_id').'"';
            $out['class'] = '1';
        }else{
            if($dept_id != session('dept_id') && session('user_id') != 'admin'){
                if(isset($condition['dept_id'])){
                    $out['dept_id'] = $condition['dept_id'];
                    $where = 't.run_id = r.run_id and r.run_id = d.run_id and r.begin_dept = "'.$condition['dept_id'].'"';
                }else{
                    $where = 't.run_id = r.run_id and r.run_id = d.run_id and r.begin_dept = "'.session('dept_id').'"';
                    $out['dept_id'] = session('dept_id');
                        }		
                $out['class'] = '1';
            }else{
                if(isset($condition['dept_id'])){
                    $where = 't.run_id = r.run_id and r.run_id = d.run_id and r.begin_dept = "'.$condition['dept_id'].'"';
                    $out['dept_id'] = $condition['dept_id'];
                }else{
                    //默认显示综合部的
                    $zhb_dept_id = M('department')->where('dept_name like "%综合部%"')->getField('dept_id');
                    $out['dept_id'] = $zhb_dept_id;
                    $where = 't.run_id = r.run_id and r.run_id = d.run_id and r.begin_dept = "'.$zhb_dept_id.'"';
                    }
                $out['class'] = '0';
                }
                    }
                    
        
        if($condition['type'] == 'leave'){//请假
            $qj_flow_id = M('flow_type')->where('flow_name like "%请假%"')->getField('flow_id');
            if(isset($condition['time'])){
                $out['contime'] = $condition['time'];
                $where .= ' and (DATE_FORMAT(t.leave_date1,"%Y-%m-%d") <= "'.$condition['time'].'" and DATE_FORMAT(t.leave_date2,"%Y-%m-%d") >= "'.$condition['time'].'") ';
            }else{
                $where .= ' and (DATE_FORMAT(t.leave_date1,"%Y-%m-%d") <= "'.date("Y-m-d").'" and DATE_FORMAT(t.leave_date2,"%Y-%m-%d") >= "'.date("Y-m-d").'")';
                    }
            $count = M()->table('flow_run r,attend_leave t,flow_data_'.$qj_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.leave_type,t.leave_type2,t.leave_duration,t.leave_date1,t.leave_date2')->where($where)->order('r.begin_time desc')->count();
            $data = M()->table('flow_run r,attend_leave t,flow_data_'.$qj_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.leave_type,t.leave_type2,t.leave_duration,t.leave_date1,t.leave_date2')->where($where)->order('r.begin_time desc')->select();
        }
        elseif($condition['type'] == 'evection'){//出差
            $cc_flow_id = M('flow_type')->where('flow_name like "%出差%"')->getField('flow_id');
            if(isset($condition['time'])){
                $out['contime'] = $condition['time'];
                $where .= ' and (DATE_FORMAT(t.evection_date1,"%Y-%m-%d") <= "'.$condition['time'].'" and DATE_FORMAT(t.evection_date2,"%Y-%m-%d") >= "'.$condition['time'].'")';
            }else{
                $where .= ' and (DATE_FORMAT(t.evection_date1,"%Y-%m-%d") <= "'.date('Y-m-d').'" and DATE_FORMAT(t.evection_date1,"%Y-%m-%d") >= "'.date('Y-m-d').'")';
            }
            $count = M()->table('flow_run r,attend_evection t,flow_data_'.$cc_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.evection_dest,t.reason,t.evection_date1,t.evection_date2')->where($where)->order('r.begin_time desc')->count();
            $data = M()->table('flow_run r,attend_evection t,flow_data_'.$cc_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.evection_dest,t.reason,t.evection_date1,t.evection_date2')->where($where)->order('r.begin_time desc')->select();
        }
        else{//外出
            $wc_flow_id = M('flow_type')->where('flow_name like "%外出%"')->getField('flow_id');
            if(isset($condition['time'])){
                $out['contime'] = $condition['time'];
                $where .= ' and d.data_56 like "%'.$condition['time'].'%"';
            }else{
                $where .= ' and d.data_56 like "%'.date('Y-m-d').'%"';
            }
            $count = M()->table('flow_run r,attend_out t,flow_data_'.$wc_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.out_type,t.out_time1,t.out_time2')->where($where)->order('r.begin_time desc')->count();
            $data = M()->table('flow_run r,attend_out t,flow_data_'.$wc_flow_id.' d')->field('r.run_id,r.flow_id,r.begin_dept,r.begin_time,r.end_time,t.user_id,t.out_type,t.out_time1,t.out_time2')->where($where)->order('r.begin_time desc')->select();
        }
//        echo M()->getLastSql();
        foreach($data as $k=>$v){
            $data[$k]['user_name'] = M('user')->where('user_id = "' . $v['user_id'] . '"')->getField('user_name');
            $data[$k]['dept_name'] = M('department')->where('dept_id = "' . $v['begin_dept'] . '"')->getField('dept_name');
            $out_date = M('flow_data_'.$v['flow_id'])->where('run_id = '.$v['run_id'])->getField('data_56');
            $data[$k]['out_date'] = date("Y-m-d",strtotime($out_date));
        }
        $out['data'] = $data;
        $out['count'] = $count;
        return $out;
    }
                    
    //考勤用户管理列表
    public function attendance() {
        $p = I('get.p');
        $limit = $this->limit;
                    
        $count = M('userinfo')->count();
        $this->users = M('userinfo')->page($p, $limit)->select();
                            
        $this->page = $this->pageLists($count, $limit);

        $this->display();
                        }

    //编缉考勤用户
    public function saveAttendance() {
        if (IS_AJAX) {
            $data = I('post.');
            if ($data['id']) {
                $res = M('userinfo')->save($data);
            } else {
                $res = M('userinfo')->add($data);
                        }

            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('attendance');
            } else {
                $return['info'] = '提交失败';
                    }
            $this->ajaxReturn($return);
        }
                        
        if (I('id')) {
            $this->info = M('userinfo')->find(I('id'));
                        }
        $this->display();
                    }

    //个人考勤记录
    public function userAttend(){
        //休假类型
        $leave_type = array('年假','病假','事假','婚假','调休','产假','女工假','护理假','工伤假','丧假','其他');
        //获取本年一月至今的时间
        $curMonth = abs(date('m'));
        for($i = 1;$i <= $curMonth;$i++){
            if($i < 10)
                $month = date("Y-0".$i);
                    else
                $month = date("Y-".$i);
            $date1 = $month.'-01';
            $date2 = date("Y-m-t", strtotime($month));
            $detail[$i] = $this->getAttend($date1,$date2,I('user_id'));
            //获取该月不同休假类型的天数
            $con = [];
            $leave_type = array('年假','病假','事假','婚假','调休','产假','女工','护理假','工伤假','丧假','其他');
            foreach($leave_type as $v){
                $leave_duration = 0;
                $con['leave_type2'] = array('like','%'.$v.'%');
                $con['user_id'] = array('like','%'.I('user_id').'%');
                $con['leave_date1'] = array('like','%'.$month.'%');
                $con['leave_date2'] = array('like','%'.$month.'%');
                $leave_data = M('attend_leave')->field('leave_duration')->where($con)->select();
                foreach($leave_data as $key=>$value){
                    if(strpos($value['leave_duration'],'小时')>0){
                        $pos_hour = strpos($value['leave_duration'],'小时');
                        $leave_data[$key] = round(substr($value['leave_duration'],0,$pos_hour)/8,2);
                    }elseif(strpos($value['leave_duration'],'天')>0 && strpos($value['leave_duration'],'半天')==0 ){
                        $leave_data[$key] = substr($value['leave_duration'],0,strpos($value['leave_duration'],'天'));
                    }elseif(strpos($value['leave_duration'],'半天')>0){
                        $leave_data[$key] = 0.5;
                    }else{
                        $leave_data[$key] = $value['leave_duration'];
                    }
                    $leave_duration += $leave_data[$key];
                }
                    
                $detail[$i]['type'][] = $leave_duration?$leave_duration:0;
                }
            foreach($detail[$i]['type'] as $k=>$v){
                $detail[$i]['leave'] += $v;
                }
                
            }
            
        //获取该用户的部门
        $userDept = M('user')->where('user_id = "'.I('user_id').'"')->getField('dept_id');
        $this->count = count($detail);
        $this->detail = $detail;
        $this->leave_type = $leave_type;
        $this->user_name = getUserName(I('user_id'));
        $this->dept_name = getDeptName($userDept);
        $this->display();
    }
    
    
    //获取部门用户(切换部门查询：级联查询)
    public function getDeptUser(){
        $dept_id = I('dept_id');
        if($dept_id){
            $users = M('user')->field('user_id,user_name')->where("user_id != 'admin' and dept_id = ".$dept_id)->select();
            $this->ajaxReturn($users);
    }
    }
    
    //绩效考核
    public function performance(){
        //分页
        $p = I('get.p', 1, 'intval');
        $this->p = $p;
        $limit = 10;
        $num = ($p - 1) * $limit + 1;
        
        //当前年
        $this->curYear = date("Y");
        $this->yearArr = array(date("Y"),date("Y")-1);
        $this->monthArr = array(1,2,3,4,5,6,7,8,9,10,11,12);
        $con = I('get.');
        
        if(isset($con['year']) && isset($con['month'])){
            $this->chooseyear = $con['year'];
            $this->month = $con['month'];
            $date1 = $con['year'].'-'.$con['month'].'-01';
            $date2 = date("Y-m-t",strtotime($con['year'].'-'.$con['month']));
            $date3 = $con['year'].'-'.$con['month'];
        }else{
            $this->curMonth = date("m");
            //默认显示本年本月全部部门的数据
            $date1 = date('Y-m-01');
            $date2 = date("Y-m-d");
            $date3 = date("Y-m");
        }
        
        
        $dept_id = M('department')->where('dept_name like "%公司领导%"')->getField('dept_id');
        $priv_no = M('user_priv')->where('user_priv like "%'.session('user_priv').'%"')->getField('priv_no');
        if($priv_no <= 40){
            if($dept_id != session('dept_id') && session('user_id') != 'admin' ){//部门领导
                $this->leader = '1';
                $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30 and u.dept_id = '.session('dept_id');
            }else{//公司领导
                $this->leader = '2';
                if(isset($con['dept_id'])){
                    $deptId = $con['dept_id'];
                    $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30 and u.dept_id = '.$con['dept_id'];
                }else{
                    $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30';
    }
            }
            $count = M()->table('user u,department d,user_priv p')->field('u.user_id,u.user_name,u.dept_id,d.dept_name')->where($where)->count();
        }
        $users = $this->getPerform($date1,$date2,$date3,$count,$where,$p,$limit,$num,'perform');
    
        
        $this->deptId = $deptId?$deptId:'';
        $this->date1 = $date1;
        $this->date2 = $date2;
        $this->date = $date3;
        $this->page = $this->pageLists($count, $limit);
        $this->users = $users;
        $this->count = $count;
        $this->display();
    }
    
    //获取考勤数据
    public function getAttend($date1,$date2,$user_id){
        $evection = 0;//出差
        $late = 0;//迟到
        $early = 0;//早退
        $all_total = 0;//出勤
        //获取用户的pin值
        $pin = M('userinfo')->where('user_id = "'.$user_id.'"')->getField('pin');
            for($j=$date1;$j<=$date2;$j=date("Y-m-d",strtotime($j)+24*3600))
            {
                $duty_arr=array();
                $checkData = array();
                //判断上、下班类型
            $where = 'pin = "'.$pin.'"  and to_days(stime)=to_days("'.$j.'")';
            $data1 = M('inoutdata')->field('min(stime) as minstime')->where($where)->order('stime desc')->find(); 
            $data2 = M('inoutdata')->field('max(stime) as maxstime')->where($where)->order('stime desc')->find(); 
//            $data = M('inoutdata')->field('min(stime) as minstime,max(stime) as maxstime')->where($where)->order('stime desc')->find(); 
            $data = array_merge($data1,$data2);
            if($data){
                    $mintime = substr($data['minstime'],11,5);
                    $maxtime = substr($data['maxstime'],11,5);
                    if($maxtime >= $mintime){
                        if($maxtime < '11:30'){
                            $register_type = 1;
                            $checkData[$register_type]['stime']= $data['minstime'];
                        }elseif($mintime > '11:30'){
                            $register_type = 2;
                            $checkData[$register_type]['stime']= $data['maxstime'];
                        }elseif($mintime < '11:30' && $maxtime > '11:30'){
                            $checkData[1]['stime']= $data['minstime'];
                            $checkData[2]['stime']= $data['maxstime'];
                        }
                    }
                }
//
                foreach($checkData as $key=>$row){
                    $duty_arr[$key] = array(
                            "duty_type"=> 0,
                            "stime"=>$row["stime"],
                    );
                }
                foreach($duty_arr as $tem)
                    $duty_type=$tem["duty_type"];
                
                if($duty_type=="" || $duty_type==0)
                    $duty_type=1;
                

            $attend_config = M('attend_config')->where('duty_type = '.$duty_type)->find();
                if($attend_config){
                    $duty_name=$attend_config["duty_name"];
                    $general=$attend_config["general"];
                    $duty_type_arr=array();
                for($i=1;$i<=2;$i++)
                    {
                        if($attend_config["duty_time".$i]!="")
                        {
                            if($i%2 != 0)
                            $duty_type_arr[$i]=array( "duty_time" => date("H:i:s",strtotime($attend_config["duty_time".$i])+5*60) ,"duty_type" => $attend_config["duty_type".$i]);
                            else
                            $duty_type_arr[$i]=array( "duty_time" => date("H:i:s",strtotime($attend_config["duty_time".$i])-5*60) ,"duty_type" => $attend_config["duty_type".$i]);
                        }		
                    }
            }else
                continue;
            $count=count($duty_type_arr);//此排班一天需要登记次数。
            $is_all=0;//出勤
            $ought_to=1;//应该考勤登记
                        
                //按日算的
            if($is_holiday=$this->check_holiday($j)!=0){//是否休息日(节假日)
                    $ought_to=0;
            }else if($is_holiday1=$this->check_holiday1($j,$general)!=0){//是否双休日
                    $ought_to=0;
            }else if($is_evection =$this->check_evection($user_id,$j)!=0){//是否出差
                    $ought_to=0;
                    $evection+=1;
                }
            foreach($duty_type_arr as $register_type => $duty_type_one)//遍历按排班需要登记的
                {
                $start_or_end=$duty_type_one["duty_type"];	//上下班：1：上班，2：下班。
                    $duty_time_ought=$duty_type_one["duty_time"];//设定的考勤时间。
                    $duty_one_arr=$duty_arr[$register_type];//相应的登记记录
                    $has_duty=0;
                    if(is_array($duty_one_arr) && $duty_one_arr['stime'] != '')
                    {
                        foreach($duty_one_arr as $key => $value)
                            $$key=$value;
                        $has_duty=1;
                    }

                    //按时间点算的。
                if($is_leave=$this->check_leave($user_id,$j,$duty_type_arr[$register_type]["duty_time"])!=0){//是否请假
                        $ought_to=0;
                }else if($is_out=$this->check_out($user_id,$j,$duty_type_arr[$register_type]["duty_time"])!=0){//是否外出
                        $ought_to=0;
                    }

                if($has_duty==1)//已经登记（都计算）
                    {
                        $register_time2=$duty_one_arr["stime"];
                        $register_time=$duty_one_arr["stime"];
                    $all_minites[$user_id][$j][$register_type] = $register_time;
                        $register_time=strtok($register_time," ");
                        $register_time=strtok(" ");
                    if($start_or_end=="1" && $this->compare_time($register_time,$duty_time_ought)==1)
                    {
                        if($ought_to!=0)
                            $late++;//迟到

                    }
                    if($start_or_end=="2" && $this->compare_time($register_time,$duty_time_ought)==-1)
                        {
                        if($ought_to!=0)
                            $early++;//早退
                        }
                    $is_all+=1;
                    }
                else if($has_duty==0 && $ought_to==1)//应该登记，没有登记的
                    {
                    $is_all+=0;
                    }
                    else
                    $is_all+=0;

                }
            if($is_all != 0){
                $all_total++;//出勤的
            }
        }
        $attend = array('all_total'=>$all_total+$evection,'evection'=>$evection,'late'=>$late,'early'=>$early); 
        return $attend;
    }
    
    //获取绩效数据
    public function getPerform($date1,$date2,$date3,$count,$where,$p,$limit,$num,$type){
        if($count){
            if($type == 'perform')
                $users = M()->table('user u,department d,user_priv p')->field('u.user_id,u.user_name,u.dept_id,d.dept_name')->where($where)->page($p, $limit)->select();
            elseif($type == 'exportPerform')
                $users = M()->table('user u,department d,user_priv p')->field('u.user_id,u.user_name,u.dept_id,d.dept_name')->where($where)->select();
        }
        if(!empty($users)){
            foreach($users as $k=>$v){
                $users[$k]['num'] = $num++;
                //该用户的公司级计划数（包含已结束和未结束的）
                $planMap = [];
                $planMap['manager|participator|executor'] = array(array('like','%'.$v['user_id'].'%'),array('like','%'.$v['user_id'].'%'),array('like','%'.$v['user_id'].'%'),'_multi'=>true);
                $planMap['level'] = 2;
                $planMap['begin_date'] = array('like','%'.$date3.'%');
                $companyPlan = M('work_plan')->where($planMap)->count();
        
                //获取公司级计划(已结束的计划)
                $planMap['sms_flag'] = 1;
                $comPlan = M('work_plan')->field('plan_id,name,begin_date,end_date,sms_flag,level,uploads,cycle')->where($planMap)->select();
    
            
                //该用户的个人计划数（包含已结束和未结束的）
                $uMap['manager|participator|executor'] = array(array('like','%'.$v['user_id'].'%'),array('like','%'.$v['user_id'].'%'),array('like','%'.$v['user_id'].'%'),'_multi'=>true);
                $uMap['level'] = 1;
                $uMap['begin_date'] = array('like','%'.$date3.'%');
                $uPlan = M('work_plan')->where($uMap)->count();
               
                //该用户的未完成计划数(公司级和个人级)
                unset($planMap['level']);
                $planMap['sms_flag'] = 0;
                $users[$k]['noFinish'] = M('work_plan')->where($planMap)->count();
               
                //获取公司级计划标的物缺失数，进度欠报次数(已结束的计划)
                $noDetail = 0;//每条计划的进度欠报次数
                $users[$k]['lostFile'] = 0;//标的物缺失数
                foreach($comPlan as $key=>$value){
                    //计算标的物缺失数
                    $file = 0;//每个计划的标的物个数
                    $work_detail = M('work_detail')->field('plan_id,uploads')->where('plan_id = '.$value['plan_id'])->select();
                    foreach($work_detail as $d_key=>$d_value){
                        if($d_value['uploads'] != '')
                            $file++;
        }
                    if($file == 0){
                        $users[$k]['lostFile']++;
    }
    
                    //计算进度欠报数
                    $detailCount = count($work_detail);//已填进度数
                    $startDate = $value['begin_date'];
                    $endDate = substr($value['end_date'],0,1) == 0?date('Y-m-d',strtotime($value['begin_date'])+3600*24*30):$value['end_date'];
                    $weekCount = round((strtotime($endDate)-strtotime($startDate))/(24*3600)/7);
                    if($value['cycle'] == 1){//一周一报
                        $commitDetail = $weekCount;
                        //获取该条计划的进度数
                    }elseif($value['cycle'] == 2){
                        $commitDetail = $weekCount*2;
                    }elseif($value['cycle'] == 3){
                        $commitDetail = 1;
                }
                    $noDetail += ($commitDetail-$detailCount)>0?($commitDetail-$detailCount):0;
                }
                $users[$k]['companyPlan'] = $companyPlan;
                $users[$k]['noDetail'] = $noDetail;
                $users[$k]['uPlan'] = $uPlan;
                $attend = $this->getAttend($date1,$date2,$v['user_id']);
               
                //获取休假天数
                $leave = 0;
                $where = 'user_id = "'.$v['user_id'].'" and (leave_date1 like "%'.$date3.'%" or leave_date2 like "%'.$date3.'%")';
                $leave_data = M('attend_leave')->field('leave_duration')->where($where)->select();
                foreach($leave_data as $l_key=>$l_value){
                    if(strpos($l_value['leave_duration'],'小时')>0){
                        $pos_hour = strpos($l_value['leave_duration'],'小时');
                        $leave_data[$l_key] = round(substr($l_value['leave_duration'],0,$pos_hour)/8,2);
                    }elseif(strpos($l_value['leave_duration'],'天')>0 && strpos($l_value['leave_duration'],'半天')==0 ){
                        $leave_data[$l_key] = substr($l_value['leave_duration'],0,strpos($l_value['leave_duration'],'天'));
                    }elseif(strpos($l_value['leave_duration'],'半天')>0){
                        $leave_data[$l_key] = 0.5;
            }else{
                        $leave_data[$l_key] = $l_value['leave_duration'];
                }
                    $leave += $leave_data[$l_key];
            }
                $users[$k]['leave'] = $leave;
                $users[$k]['all_total'] = $attend['all_total'];
                $users[$k]['evection'] = $attend['evection'];
                $users[$k]['late'] = $attend['late'];
                $users[$k]['early'] = $attend['early'];
        
                //获取加班时长
                $overtime = 0;
                $where = 'user_id = "'.$v['user_id'].'" and (start_time like "%'.$date3.'%" or end_time like "%'.$date3.'%")';
                $overtime_data = M('attendance_overtime')->field('overtime_hours')->where($where)->select();
        
                foreach($overtime_data as $o_key=>$o_value){
                    if(strpos($o_value['overtime_hours'],'个小时') >0 ){
                        $pos_hour = strpos($o_value['overtime_hours'],'个小时');
                        $overtime_data[$o_key] = substr($o_value['overtime_hours'],0,$pos_hour);
                    }elseif(strpos($o_value['overtime_hours'],'小时')>0 ){
                        $pos_hour = strpos($o_value['overtime_hours'],'小时');
                        $overtime_data[$o_key] = substr($o_value['overtime_hours'],0,$pos_hour);
            }else{
                        $overtime_data[$o_key] = $o_value['overtime_hours'];
            }
                    $overtime += $overtime_data[$o_key];
        }
                $users[$k]['overtime'] = $overtime;
            }
        }
        return $users;
            }
    
    //导出绩效
    public function exportPerform(){
        $con = I('get.');
        if(isset($con['year']) && isset($con['month'])){
            $this->chooseyear = $con['year'];
            $this->month = $con['month'];
            $date1 = $con['year'].'-'.$con['month'].'-01';
            $date2 = date("Y-m-t",strtotime($con['year'].'-'.$con['month']));
            $date3 = $con['year'].'-'.$con['month'];
            $timeName = $con['year'].'年'.$con['month'].'月';
        }else{
            $this->curMonth = date("m");
            //默认显示本年本月全部部门的数据
            $date1 = date('Y-m-01');
            $date2 = date("Y-m-d");
            $date3 = date("Y-m");
            $timeName = date('Y').'年'.date('m').'月';
    }

        $dept_id = M('department')->where('dept_name like "%公司领导%"')->getField('dept_id');
        $priv_no = M('user_priv')->where('user_priv like "%'.session('user_priv').'%"')->getField('priv_no');
        if($priv_no <= 40){
            if($dept_id != session('dept_id') && session('user_id') != 'admin' ){//部门领导
                $this->leader = '1';
                $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30 and u.dept_id = '.session('dept_id');
            }else{//公司领导
                $this->leader = '2';
                if(isset($con['dept_id'])){
                    $deptId = $con['dept_id'];
                    $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30 and u.dept_id = '.$con['dept_id'];
                }else{
                    $where = 'u.dept_id = d.dept_id and u.user_priv = p.user_priv and u.dept_id != 0 and p.priv_no >= 30';
            }
            }
            $count = M()->table('user u,department d,user_priv p')->field('u.user_id,u.user_name,u.dept_id,d.dept_name')->where($where)->count();
        }

        $users = $this->getPerform($date1,$date2,$date3,$count,$where,$p,$limit,$num,'exportPerform');
        $headArr = array("部门","人员","公司级计划数","未完成计划数","标的物缺失数","进度欠报次数","个人计划数","迟到次数","早退次数","出差天数","请假天数","加班时长");
//        echo '<pre>',print_r($users);die;
        $data = array();
        foreach($users as $k=>$v){
            $data[$k]['dept_name'] = $v['dept_name'];
            $data[$k]['user_name'] = $v['user_name'];
            $data[$k]['companyPlan'] = $v['companyPlan'];
            $data[$k]['noFinish'] = $v['noFinish'];
            $data[$k]['lostFile'] = $v['lostFile'];
            $data[$k]['noDetail'] = $v['noDetail'];
            $data[$k]['uPlan'] = $v['uPlan'];
            $data[$k]['late'] = $v['late'];
            $data[$k]['early'] = $v['early'];
            $data[$k]['evection'] = $v['evection'];
            $data[$k]['leave'] = $v['leave'];
            $data[$k]['overtime'] = $v['overtime'];
        }
        echo exportExcel('绩效考核（'.$date3.'）', $headArr, $data);

        }

}
